package com.tanqidi.arcgisandroid.ui.layerConfig

import android.os.Bundle
import android.text.TextUtils
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.tabs.TabLayoutMediator
import com.tanqidi.arcgisandroid.base.utils.showToast
import com.tanqidi.arcgisandroid.data.layerConfig.Layer
import com.tanqidi.arcgisandroid.data.layerConfig.Layer.Companion.TYPE_POINT
import com.tanqidi.arcgisandroid.data.layerConfig.Layer.Companion.TYPE_POLYGON
import com.tanqidi.arcgisandroid.data.layerConfig.Layer.Companion.TYPE_POLYLINE
import com.tanqidi.arcgisandroid.data.project.Project
import com.tanqidi.arcgisandroid.databinding.FragmentLayerConfigBinding
import com.tanqidi.arcgisandroid.databinding.ItemDialogInputBinding
import com.tanqidi.arcgisandroid.ui.layerConfig.subLayer.SubLayerAdapter
import com.tanqidi.arcgisandroid.ui.layerConfig.subLayer.SubLayerFragment
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class LayerConfigFragment : Fragment() {

    private lateinit var binding:FragmentLayerConfigBinding
    private val layerConfigViewModel by viewModels<LayerConfigViewModel>()
    private val args by navArgs<LayerConfigFragmentArgs>()
    private lateinit var project: Project

    private val subFragmentList = mutableListOf<SubLayerFragment>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentLayerConfigBinding.inflate(layoutInflater)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        initTopBar()
        initViewEvent()
        initLiveData()
        initTabLayoutAndViewPage()
        return binding.root
    }

    /**
     * 这里是给subFragment调用的，viewPage中的子页面跳转不过去的
     */
    fun goFieldConfigFragment(projectName:String, layerName:String){
        val action = LayerConfigFragmentDirections.actionLayerConfigFragmentToFieldConfigFragment(projectName, layerName)
        findNavController().navigate(action)
    }

    fun flushTabCount(type: String, count: Int) {
        val index = when(type) {
            TYPE_POINT -> {0}
            TYPE_POLYLINE -> {1}
            TYPE_POLYGON -> {2 }
            else -> {0}
        }
        val orCreateBadge = binding.tabLayout.getTabAt(index)!!.orCreateBadge
        //如果只有0个，就不用显示出来了
        if (count == 0) {
            orCreateBadge.isVisible = false
            orCreateBadge.clearNumber()
        } else {
            orCreateBadge.isVisible = true
            orCreateBadge.number = count
        }
    }

    private fun initTabLayoutAndViewPage() {
        project = layerConfigViewModel.getProjectByName(args.projectName)
        subFragmentList.apply {
            clear()
            add(SubLayerFragment.newInstance(TYPE_POINT, args.projectName))
            add(SubLayerFragment.newInstance(TYPE_POLYLINE, args.projectName))
            add(SubLayerFragment.newInstance(TYPE_POLYGON, args.projectName))
        }
        val tabLayout = binding.tabLayout
        val viewPager2 = binding.viewPager2

        val subLayerAdapter = SubLayerAdapter(this, subFragmentList)
        //因为只有三个页面所以不做缓存，全部显示出来
        viewPager2.offscreenPageLimit = subFragmentList.size
        viewPager2.isSaveEnabled = false

        viewPager2.adapter = subLayerAdapter
        TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
            //这里嘛，因为上面newInstance已经把title标题传入了，这里直接从argument里面拿出来用就行了
            tab.text = subFragmentList[position].requireArguments().get(SubLayerFragment.LAYER_TYPE) as String
        }.attach()
    }

    private fun initViewEvent() {
        binding.addFloatingActionButton.setOnClickListener {
            val dialogBinding = ItemDialogInputBinding.inflate(layoutInflater)
            val dialog = MaterialAlertDialogBuilder(requireContext())
                .setTitle("新建图层")
                .setView(dialogBinding.root)
                .show()

            dialogBinding.apply {
                accept.setOnClickListener {
                    val content = textInputEditText.text.toString().trim()
                    if(TextUtils.isEmpty(content)){
                        textInputLayout.error = "内容不可为空"
                    } else {
                        //开始创建图层layer
                        val currentSubFragment = subFragmentList[binding.tabLayout.selectedTabPosition]
                        val type = currentSubFragment.requireArguments().get(SubLayerFragment.LAYER_TYPE) as String
                        project.layers.add(Layer().apply {
                            this.type = type
                            name = content
                        })
                        //既然project放了一个新的layer图层了，覆盖一下本地的配置文件
                        layerConfigViewModel.saveProject(project)
                        //创建完了让子sub的fragment重新加载一下显示出来
                        showToast("创建成功")
                        currentSubFragment.flushData()
                        dialog.dismiss()
                    }
                }
            }
        }
    }

    private fun initTopBar(){
        //返回键
        binding.topAppBar.setNavigationOnClickListener { findNavController().navigateUp() }
    }

    private fun initLiveData(){

    }
}